package com.ruoyi.tools;

import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import javax.annotation.PostConstruct;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.tools.PublishMsg;
import com.ruoyi.tools.SubscribeMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;


@Component
public class WxTool {

    @Autowired
    private ISysConfigService configService;

    @Autowired
    private RedisCache redisCacheService;

    private static ISysConfigService sysConfigService;

    private static RedisCache redisCache;

    private static String ACCESS_TOKEN_KEY = "accessToken";

    private static String loginUrl = "https://api.weixin.qq.com/sns/jscode2session";//登录地址
    private static String atUrl = "https://api.weixin.qq.com/cgi-bin/token";//access_token
    private static String phoneUrl = "https://api.weixin.qq.com/wxa/business/getuserphonenumber";//获取手机号

    private static String msgUrl = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send";//模板消息


    @PostConstruct
    public void init() {
        sysConfigService = this.configService;
        redisCache = this.redisCacheService;
    }

    /**
     * 获取登录信息
     *
     */
    public static String getLoginInfo(String code) {
        String appId = sysConfigService.selectConfigByKey("wx.appid");
        String appSecret = sysConfigService.selectConfigByKey("wx.appsecret");

        String params = "appid=" + appId + "&secret=" + appSecret + "&js_code=" + code + "&grant_type=authorization_code";
        String sr = HttpRequest.sendGet(loginUrl, params);
        //解析相应内容（转换成json对象）
        JSONObject json = JSONObject.parseObject(sr);
        //用户的唯一标识（openid）
        String openid = (String) json.get("openid");
        return openid;
    }


    /**
     * 获取手机号码
     *
     */
    public static String getPhoneNum(String code) {
        String access_token = getAccessToken();

        JSONObject json = new JSONObject();
        json.put("code", code);
        String jsonstr = JSONObject.toJSONString(json);
        String ret = HttpRequest.sendPost(phoneUrl+"?access_token=" + access_token, jsonstr);

        JSONObject res = JSONObject.parseObject(ret);

        Integer errcode = res.getInteger("errcode");
        if(errcode==0) {
            JSONObject phoneinfo = res.getJSONObject("phone_info");
            String phone = phoneinfo.getString("phoneNumber");
            return phone;
        }else {
            return null;
        }
    }


    public static String getAccessToken() {

        String appId = sysConfigService.selectConfigByKey("wx.appid");
        String appSecret = sysConfigService.selectConfigByKey("wx.appsecret");

        String at = "";

        if(redisCache.hasKey(ACCESS_TOKEN_KEY)) {//未过期
            at = (String) redisCache.getCacheObject(ACCESS_TOKEN_KEY);;
        }else {//已过期 重新获取
            String params = "appid=" +appId + "&secret=" + appSecret + "&grant_type=client_credential";
            String sr = HttpRequest.sendGet(atUrl, params);
            JSONObject json = JSONObject.parseObject(sr);
            at = json.getString("access_token");
            //放入redis缓存 过期时间110分钟
            redisCache.setCacheObject(ACCESS_TOKEN_KEY,at,110, TimeUnit.MINUTES);
        }
        return at;
    }


    /**
     * 发送消息
     * @param subscribeMessage
     */
    public static void serndMsg(SubscribeMessage subscribeMessage) {

//		Map map = new HashMap<>();
//	     map.put("thing4", new TemplateData("3.15我承诺"));
//	     map.put("thing2", new TemplateData("诚信经营，文明服务，诚信经营承诺书签署"));
//	     map.put("date3", new TemplateData("2022年03月15日"));
//	     map.put("time16", new TemplateData("2023年03月15日"));
//
//		SubscribeMessage subscribeMessage = new SubscribeMessage();
//		subscribeMessage.setAccess_token(access_token);
//       subscribeMessage.setTouser("oORFA489t5HsWADi-KjH0ZCQd37k");
//       subscribeMessage.setTemplate_id("i0CHVI0_prPv4V-5c2f9pvQEbBC_BBTLJQ4CHjPNqOo");
//       subscribeMessage.setPage("pages/views/actdetail/index?opentype=1");
//       subscribeMessage.setMiniprogram_state("developer");
//       subscribeMessage.setData(map);


//		String access_token = getAccessToken();
        String access_token = subscribeMessage.getAccess_token();

        String jsonstr = JSONObject.toJSONString(subscribeMessage);

        String ret = HttpRequest.sendPost(msgUrl+"?access_token=" + access_token, jsonstr);
        System.out.println(ret);
    }

    public static void sendMsg(String openid, Map map,String tplid,String page) {
        //发送模板消息
        String access_token = getAccessToken();

        SubscribeMessage subscribeMessage = new SubscribeMessage();
        //access_token
        subscribeMessage.setAccess_token(access_token);
        //openId
        subscribeMessage.setTouser(openid);
        //模板消息ID
        subscribeMessage.setTemplate_id(tplid);
        //跳转小程序类型：developer为开发版；trial为体验版；formal为正式版；默认为正式版
        subscribeMessage.setMiniprogram_state("trial");
        //模板内容
        subscribeMessage.setData(map);
        //跳转小程序页面
        if(page!=null) {
            subscribeMessage.setPage(page);
        }

        //发送
        serndMsg(subscribeMessage);
    }

    /**
     * 多线程发送消息
     * @param
     * @param map
     * @param tplid
     * @param page
     */
    public static void sendMsgMultithreading(List<String> openidlist, Map map, String tplid, String page) {

        PublishMsg pmt = new PublishMsg();

        pmt.sendMsg(openidlist, map,tplid,page);

    }

}
